import api from "../../utils/apiInstance";
import {getUserInfo} from '../../utils/store';

const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    baseUrl: app.globalData.baseUrl,
    towerUrl: app.globalData.towerUrl,
    userDept: getUserInfo().siocDepartCode.split(','),
    userSapId: getUserInfo().siocSapNo,
    checkFlag: false,
    longitude: '',
    latitude: '',
    targetLat: '',
    targetLon: '',
    checkItem: {},
    checkRecords: [],
    itemId: ''
  },
  onPullDownRefresh() {
    // 处理下拉刷新的逻辑
    this.getItemInfo(this.data.itemId);
    wx.stopPullDownRefresh(); // 刷新完毕后停止下拉刷新动画
  },

  async getItemInfo(itemId){
    const res = await api.get(`/checkItem/wx/getItemInfo`,{'id':itemId});
    this.setData({
      checkItem: res.data,
      checkFlag: this.data.userDept.includes(res.data.dept)
    })
    this.getRecords(itemId);
  },

  getRecords: function(itemId){
    var that = this;
    wx.request({
      url: that.data.baseUrl + '/checkRecord/wx/getRecords?itemId='+itemId,
      method: 'GET',
      header: {
        'Content-Type': 'application/json' // 请求头  
      },
      success(res) {
        console.log('获取检查设备检查记录:', res.data);
        var data=res.data;
        that.setData({
          checkRecords: data.rows
        })
      }
    });
  },

  checkDistance: function () {
    const targetLat = this.data.checkItem.latitude;
    const targetLon = this.data.checkItem.longitude;
    const currentLat = this.data.latitude;
    const currentLon = this.data.longitude;
    const R = 6371e3; // 地球半径，单位为米

    if(!targetLat || !targetLon){
      return true;
    }

    const dLat = (currentLat - targetLat) * Math.PI / 180;
    const dLon = (currentLon - targetLon) * Math.PI / 180;

    const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
        Math.cos(targetLat * Math.PI / 180) * Math.cos(currentLat * Math.PI / 180) *
        Math.sin(dLon / 2) * Math.sin(dLon / 2);
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    const distance = R * c; // 计算出的距离，单位为米

    console.log('距离：', distance, '米');
    return distance <= this.data.distanceConf; // 判断是否在范围内
  },

  goCheck(){
    const isWithinRange = this.checkDistance();
    if(isWithinRange){
      wx.navigateTo({
        url: '/pages/check-do/check-do?itemId='+this.data.itemId,
      })
    }else {
      wx.showToast({
        title: '不在点检范围内',
        icon: 'none'
      });
    }
  },

  getLocation: function () {
    const that = this;
    wx.getLocation({
      type: 'gcj02', // 返回可以用于 `wx.openLocation` 的经纬度
      success(res) {
        console.log('当前位置：', res);
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude
        });
      },
      fail(err) {
        console.error('获取位置失败：', err);
        wx.showToast({
          title: '获取位置失败',
          icon: 'none'
        });
      }
    });
  },

  getDistanceConf() {
    var that = this;
    wx.request({
      url: that.data.towerUrl + '/api/tower/moa/wx/getEnumsByKey?key=check_distance',
      method: 'POST',
      header: {
        'Content-Type': 'application/json' // 请求头
      },
      success(res) {
        console.log('获取距离配置:', res.data);
        that.setData({
          distanceConf: res.data.data[0].keyValue
        })
      }
    });
  },

  setLocation: function () {
    var that = this;
    wx.showModal({
      title: '提示',
      content: '请确认设置定位',
      showCancel: true,
      success: async function (res) {
        if (res.confirm) {
          const res2 = await api.post(`/checkItem/wx/update`,{
            id : that.data.itemId,
            latitude : that.data.latitude,
            longitude : that.data.longitude,
            updateBy: getUserInfo().siocCnName,
          },);
          if (200 == res2.code) {
            wx.showModal({
              title: '提示',
              content: res2.msg,
              showCancel: false,
              success: function (res3) {
                if (res3.confirm) {
                  that.getItemInfo(that.data.itemId);
                }
              }
            });
          } else {
            that.getList();
            wx.showToast({
              title: res.data.msg,
              icon: 'none'
            });
          }
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(query) {
    this.getItemInfo(query.scene);
    this.getDistanceConf();
    this.getLocation();
    this.setData({
      itemId: query.scene
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})